package clustersimulator;
import java.util.List;
import net.sf.javaml.core.Instance;

public class ProcessingCluster {

	/*
	 * Number of nodes within this cluster
	 */
	private int nodes;

	/*
	 * Centroid
	 */
	private Instance centroid;

	/*
	 * Sum of all cycles any node spent idling
	 */
	private long idleNodeCycles;

	/*
	 * Current job assigned for processing
	 */
	protected Job currentJob;

	/*
	 * Processing time left until job finishes
	 */
	private double processingTime;

	/*
	 * Whether this cluster is busy or idle
	 */
	private boolean isAvailable;

	/*
	 * Dump for finished jobs
	 */
	private List<Job> jobDump;

	public ProcessingCluster(int nodes, Instance centroid, List<Job> dump) {
		this.nodes = nodes;
		this.centroid = centroid;
		this.idleNodeCycles = 0;
		this.isAvailable = true;
		this.jobDump = dump;
	}

	public Instance getCentroid() {
		return centroid;
	}

	public void processJob(long clock) {
		// only process if cluster is set to unavailable
		if (!isAvailable) {
			int adoc = currentJob.getADOC();

			if (adoc <= nodes) {
				processingTime = processingTime - 1;

				idleNodeCycles += nodes - adoc;
			} else {
				processingTime = processingTime - (double) nodes / (double) adoc;
			}

			if (processingTime <= 0) {
				isAvailable = true;
				currentJob.setTimeFinished(clock);
				jobDump.add(currentJob);
			}
		} else {
			idleNodeCycles += nodes;
		}
	}

	public void assignJob(Job job) {
		this.currentJob = job;
		this.isAvailable = false;
		this.processingTime = job.getProcessingTime();
	}

	public boolean isAvailable() {
		return this.isAvailable;
	}

	public int size() {
		return this.nodes;
	}

	public long getIdleNodeCycles() {
		return this.idleNodeCycles;
	}
}
